package com.auxgroup.hr.front.commons.utils;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.UUID;

import javax.imageio.stream.FileImageInputStream;
import javax.imageio.stream.FileImageOutputStream;

import com.auxgroup.hr.front.commons.exception.FrontException;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.Base64Utils;

import com.auxgroup.hr.front.commons.BaseRetCode;
import com.auxgroup.hr.front.commons.exception.FrontException;

/**
 * 图片与byte数组转换
 * @author lv-PC
 */
public class File2Byte {
	
	private static final Logger logger = LoggerFactory.getLogger(File2Byte.class);


    //图片到byte数组
    public static  byte[] image2byte(String path) {
    	logger.info("image2byte start "); 
        byte[] data = null;
        FileImageInputStream input = null;
        try {
            input = new FileImageInputStream(new File(path));
            ByteArrayOutputStream output = new ByteArrayOutputStream();
            byte[] buf = new byte[1024];
            int numBytesRead = 0;
            while ((numBytesRead = input.read(buf)) != -1) {
                output.write(buf, 0, numBytesRead);
            }
            data = output.toByteArray();
            output.close();
            input.close();
            logger.info("image2byte success "); 
        } catch (FileNotFoundException ex1) {
        	logger.info("image2byte error: ",ex1); 
        } catch (IOException ex1) {
        	logger.info("image2byte error: ",ex1); 
        }
        return data;
    }
    
    /** 
    * 获得指定文件的byte数组 
    */  
    public static byte[] file2Bytes(File file){
       byte[] buffer = null;  
       try {  
           FileInputStream fis = new FileInputStream(file);  
           ByteArrayOutputStream bos = new ByteArrayOutputStream();  
           byte[] b = new byte[1024];  
           int n;  
           while ((n = fis.read(b)) != -1) {  
               bos.write(b, 0, n);  
           }  
           fis.close();  
           bos.close();  
           buffer = bos.toByteArray();  
       } catch (FileNotFoundException e) {  
    	   logger.info("file2Bytes error: ",e); 
       } catch (IOException e) {  
    	   logger.info("file2Bytes error: ",e); 
       }  
       return buffer;  
   }

    /**
     * byte数组到图片
     * @param data
     * @param path 
     * @param isCover 是否覆盖
     * @return
     */
    public static Boolean byte2image(byte[] data, String path,Boolean isCover) {
    	logger.info("byte2image start path={},isCover={}",path,isCover); 
        if (data == null || data.length < 3 || StringUtils.isEmpty(path)) return false;
        try {
        	File jpg = new File(path);
        	if(jpg.exists()){
        		logger.info("emplPhoto {} has exists ",path); 
        		if(isCover){
        			jpg.delete();
        			jpg.createNewFile();
           		 	FileImageOutputStream imageOutput = new FileImageOutputStream(jpg);
                    imageOutput.write(data, 0, data.length);
                    imageOutput.close();
                    logger.info("byte2image success "); 
        		}else{
        			return true;
        		}
        	}else{
        		if(!jpg.getParentFile().exists()){
       			 	jpg.getParentFile().mkdirs();
    	   		 }else{
    	   			 jpg.createNewFile();
    	   		 }
       		 	FileImageOutputStream imageOutput = new FileImageOutputStream(jpg);
                imageOutput.write(data, 0, data.length);
                imageOutput.close();
                logger.info("byte2image success "); 
        	}
        	return true;
        } catch (Exception ex) {
        	logger.info("byte2image error: ",ex); 
        	return false;
        }
    }
    
    /**
     * byte转文件
     * @param file
     * @param path
     * @return
     */
    public static Boolean byte2File(byte[] file,String path){
    	logger.info("byte2File start "); 
        if (file.length < 3 || path.equals("")) return false;
        try {
        	File filepath = new File(path);
        	if(!filepath.exists()){
        		FileOutputStream  outPut = new FileOutputStream(filepath);
        		outPut.write(file, 0, file.length);
    			outPut.close();
        	}
	        logger.info("byte2File success "); 
        	return true;
        } catch (Exception ex) {
        	logger.info("byte2File error: ",ex); 
        	return false;
        }
    }
    
    /**
     * base64转图片byte
     * @param base64Data
     * @param imgPath 不带文件名
     * @return
     */
    public static byte[] base64ToImgByte(String base64Data,String imgPath){
    	logger.info("开始解析图片并上传");
		String dataPrix = "";
        String data = "";
		String [] d = base64Data.split("base64,");
        if(d != null && d.length == 2){
            dataPrix = d[0];
            data = d[1];
        }else{
            throw new FrontException(BaseRetCode.CODE_ERROR_EMPPHOTO_NOT_ALLOWED);
        }
        String suffix = getSuffix(dataPrix);
        logger.info("对数据进行解析，获取文件名和流数据");
        String tempFileName = UUID.randomUUID().toString()+"."+suffix;
        String filePath = imgPath+tempFileName;
        logger.info("生成文件为："+filePath);
        File file = new File(filePath);
        try {
			file.createNewFile();
	        byte[] bs = Base64Utils.decodeFromString(data);
	        FileUtils.writeByteArrayToFile(file, bs);
	        byte[] returnByte = image2byte(file.getPath());
	        file.delete();
	        return returnByte;
		} catch (IOException e) {
			logger.error("hirephoto base64 To img fail",e);
			return null;
		}
    }
    
    /**
     * 根据图片的base64码获取图片格式
     * @param base64Data
     * @return
     */
    public static String getImgSuffixFromBase64(String base64Data){
    	String dataPrix = "";
		String [] d = base64Data.split("base64,");
        if(d != null && d.length == 2){
            dataPrix = d[0];
        }else{
            throw new FrontException(BaseRetCode.CODE_ERROR_EMPPHOTO_NOT_ALLOWED);
        }
        return getSuffix(dataPrix);
    }
    
    /**
     * 根据base64头获取图片格式
     * @param dataPrix
     * @return
     */
    private static String getSuffix(String dataPrix){
    	String suffix = "";
        //编码的jpeg图片数据
        if("data:image/jpeg;".equalsIgnoreCase(dataPrix)){
            suffix = "jpg";
        //编码的icon图片数据
        } else if("data:image/x-icon;".equalsIgnoreCase(dataPrix)){
            suffix = "ico";
        //编码的gif图片数据
        } else if("data:image/gif;".equalsIgnoreCase(dataPrix)){
            suffix = "gif";
        //编码的png图片数据    
        } else if("data:image/png;".equalsIgnoreCase(dataPrix)){
            suffix = "png";
        }else{
        	throw new FrontException(BaseRetCode.CODE_ERROR_EMPPHOTO_NOT_ALLOWED);
        }
        return suffix;
    }
}